<template>
  <view class="flex-col page">
    <view class="flex-col justify-start">
      <view class="flex-col pos">

        <!-- 实验日志详表卡片 - 移到最上方 -->
        <view class="infocard_full">
          <!-- 搜索框和刷新按钮在同一行 -->
          <view class="flex-row items-center search-refresh-container">
            <!-- 搜索实验日志 -->
            <view class="search-box">
              <input
                  class="search-input"
                  v-model="searchKeyword"
                  placeholder="搜索实验日志..."
                  @input="handleSearch"
              />
            </view>

            <!-- 刷新日志按钮 -->
            <view class="refresh-btn" @click="refreshDiary">
              <image class="refresh-icon" src="../../static/images/refresh-icon.png" />
              <text class="refresh-text">刷新日志</text>
            </view>
          </view>

          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 设备筛选 -->
            <view class="filter-item">
              <text class="filter-label">设备筛选:</text>
              <uni-data-select
                  class="filter-select"
                  v-model="selectedEquip"
                  :localdata="equipList"
                  @change="handleEquipChange"
              ></uni-data-select>
            </view>

            <!-- 日志级别(可以根据实际需求修改为实验类型等) -->
            <view class="filter-item">
              <text class="filter-label">日志级别:</text>
              <uni-data-select
                  class="filter-select"
                  v-model="selectedLevel"
                  :localdata="levelList"
                  @change="handleLevelChange"
              ></uni-data-select>
            </view>

            <!-- 日期范围 -->
            <view class="filter-item">
              <text class="filter-label">日期范围:</text>
              <uni-datetime-picker
                  class="date-picker"
                  type="daterange"
                  v-model="dateRange"
                  @change="handleDateChange"
                  :clear-icon="false"
              />
            </view>
          </view>

          <!-- 统计信息 -->
          <view class="flex-row items-center">
            <uni-section class="range" title="">
              <uni-data-select v-model="value" :localdata="range" @change="change"></uni-data-select>
            </uni-section>
            <view class="ml-26 flex-row items-center flex-1 group_10">
              <image class="shrink-0 image_4"
                     src="../../static/images/9ef18d2963ccd2de21288bc618721ddb.png" />
              <text class="font_4 text_14">{{allExperNum}}次</text>
              <image class="shrink-0 image_5"
                     src="../../static/images/dc8cc9558a90f96262a06fa63f88e618.png" />
              <text class="font_4 text_15">{{(allExperTime/60).toFixed(1)}}h</text>
              <image class="shrink-0 image_6"
                     src="../../static/images/65ed370e53cdd654117ac228922baa6a.png" />
              <text class="font_4 text_16">{{(allExperRiseTime/60).toFixed(1)}}h</text>
            </view>
          </view>

          <!-- 添加卡片头部样式 -->
          <view class="card-header">
            <view class="section_11"></view>
            <text class="text_10">实验日志详表</text>
          </view>

          <!-- 日志列表 -->
          <view class="mt-16 flex-col">
            <view class="flex-row items-center self-stretch"
                  v-for="(item,index) in filteredDiaryRecord"
                  :index="index"
                  :key="index">
              <view class="flex-col shrink-0 group_12">
                <view class="flex-col justify-start items-start ">
                  <view class="section_7"></view>
                </view>
              </view>
              <view class="flex-col items-center shrink-0 group_11 ml-15">
                <text class="font_6 text_17">{{ getWeekday(index) }}</text>
              </view>
              <view class="flex-col items-start flex-1 ml-15">
                <text class="font_5">实验{{item.experNum}}次,总实验时长{{(item.timeLab / 60).toFixed(1)}}h,总加热时长{{(item.riseTime / 60).toFixed(1)}}h</text>
              </view>
            </view>

            <view class="flex-row self-stretch">
              <view class="flex-col justify-start shrink-0 relative group_14">
                <view class="section_6"></view>
                <view class="section_8 pos_3"></view>
              </view>
              <view class="flex-col items-start flex-1 self-start group_15 ml-15">
              </view>
            </view>
          </view>
        </view>

        <!-- 用户活跃度卡片 - 移到下方 -->
        <view class="chart-card">
          <view class="card-header">
            <view class="section_11"></view>
            <text class="text_10">用户活跃度</text>
          </view>

          <view class="charts-box">
            <qiun-data-charts type="column" :opts="opts" :chartData="chartData" :animation="false">
            </qiun-data-charts>
          </view>
        </view>

      </view>
    </view>
  </view>
</template>

<script>
import {
  _searchequipExcel
} from '@/service/history.js'
import {
  _diaryRecord
} from '@/service/history.js'

export default {
  data() {
    return {
      serialnum_equip: '',
      account: '',
      localDate: '',
      value: 0,
      index:0,
      range: [
        {
          value: 0,
          text: "本周"
        },
        {
          value: 1,
          text: "本月"
        },
        {
          value: 2,
          text: "本年"
        },
        {
          value: 3,
          text: "可用至今"
        },
      ],
      chartData: {
        categories: [
          "本周", "本月", "本年", "可用至今"],
        series: [{
          name: "用户活跃度",
          data: []
        }]
      },
      opts: {
        color: ["#3CA272", "#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#FC8452", "#9A60B4",
          "#ea7ccc"
        ],
        padding: [15, 15, 0, 5],
        enableScroll: false,
        legend: {},
        xAxis: {
          disableGrid: true
        },
        yAxis: {
          data: [{
            min: 0
          }]
        },
        extra: {
          column: {
            type: "group",
            width: 30,
            activeBgColor: "#000000",
            activeBgOpacity: 0.08
          }
        }
      },
      seriesData: [],
      diaryRecord:[],//列表数据
      filteredDiaryRecord: [], // 筛选后的数据
      allExperNum:0,
      allExperTime:0,
      allExperRiseTime:0,

      // 新增筛选相关数据
      searchKeyword: '', // 搜索关键词
      selectedEquip: 0, // 选中的设备
      selectedLevel: 0, // 选中的日志级别
      dateRange: [], // 日期范围

      // 设备列表(根据实际情况调整)
      equipList: [
        { value: 0, text: "所有设备" },
        { value: 1, text: "设备1" },
        { value: 2, text: "设备2" },
        { value: 3, text: "设备3" }
      ],

      // 日志级别列表(可根据实际需求修改)
      levelList: [
        { value: 0, text: "全部" },
        { value: 1, text: "普通" },
        { value: 2, text: "重要" },
        { value: 3, text: "紧急" }
      ]
    };
  },
  mounted() {
    try {
      const value = uni.getStorageSync('userInfo');
      if (value != null) {
        this.account = value.accountNum
        console.log(this.account);
      }
    } catch (e) {
      console.error(e);
    }
    this.DateTime()
    this.equipdiaryData()

  },
  onReady() {
    const self = this;
    try {
      setTimeout(() => {
        self.DiaryRecord()
      },300)

    } catch (e) {
      console.log(e);
    }
  },
  //点击函数传递的设备号
  onLoad(res) {
    this.serialnum_equip = res.serialnum_equip;
  },
  methods: {
    onClickItem(e) {
      if (this.current != e.currentIndex) {
        this.current = e.currentIndex;
      }
    },
    DateTime() //本地化日期
    {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      this.localDate = `${year}-${month}-${day}`;
    },
    //调用接口函数获取图表数据
    async equipdiaryData() {
      //传给后端需要的数据
      let data = {
        account_user: this.account,
        serialnum_equip: this.serialnum_equip
      }
      let res = await _searchequipExcel(data)
      console.log(res.data)
      let diary = res.data
      //for循环从返回的数据中获取本日、本周、本月、本年、可用至今的活跃度并将其放入数组seriesData中
      for (let i = 1; i < diary.length; i++) {
        this.seriesData.push(diary[i][3])
      }
      //将存储活跃度的数组赋值给表格的纵坐标
      this.chartData.series[0].data = this.seriesData;
      if (res.flag) {
        console.log('调用成功')
      } else {
        console.log('失败')
      }
    },
    //默认日志列表
    async DiaryRecord() {
      //调用接口获取详细日志数据
      let data={
        accountUser:this.account,
        serialnum: this.serialnum_equip,
        num:0
      }
      let res=await _diaryRecord(data)
      if(res.flag){
        console.log(res.data)
        this.diaryRecord = res.data;
        this.filteredDiaryRecord = res.data; // 初始化筛选数据
        this.allExperNum = 0;
        this.allExperTime = 0;
        this.allExperRiseTime = 0;

        for(let i=0;i<this.diaryRecord.length;i++){
          this.allExperNum+=this.diaryRecord[i].experNum
          this.allExperTime+=this.diaryRecord[i].timeLab
          this.allExperRiseTime+=this.diaryRecord[i].riseTime
        }
      }
    },
    async change(newValue) {
      console.log('选中的新数值为:', newValue);
      this.index=newValue
      //调用接口获取详细日志数据
      let data={
        accountUser:this.account,
        serialnum: this.serialnum_equip,
        num:newValue
      }
      let res=await _diaryRecord(data)
      if(res.flag){
        console.log(res.data)
        this.diaryRecord = res.data;
        this.applyFilters(); // 应用筛选
        this.allExperNum = 0;
        this.allExperTime = 0;
        this.allExperRiseTime = 0;

        for(let i=0;i<this.diaryRecord.length;i++){
          this.allExperNum+=this.diaryRecord[i].experNum
          this.allExperTime+=this.diaryRecord[i].timeLab
          this.allExperRiseTime+=this.diaryRecord[i].riseTime
        }
      }
    },

    // 新增方法:刷新日志
    refreshDiary() {
      uni.showLoading({
        title: '刷新中...'
      });
      this.DiaryRecord().then(() => {
        uni.hideLoading();
        uni.showToast({
          title: '刷新成功',
          icon: 'success'
        });
      });
    },

    // 新增方法:搜索处理
    handleSearch() {
      this.applyFilters();
    },

    // 新增方法:设备筛选
    handleEquipChange(value) {
      console.log('设备筛选:', value);
      this.applyFilters();
    },

    // 新增方法:日志级别筛选
    handleLevelChange(value) {
      console.log('级别筛选:', value);
      this.applyFilters();
    },

    // 新增方法:日期范围筛选
    handleDateChange(value) {
      console.log('日期范围:', value);
      this.dateRange = value;
      this.applyFilters();
    },

    // 新增方法:应用所有筛选条件
    applyFilters() {
      let filtered = [...this.diaryRecord];

      // 搜索关键词筛选
      if (this.searchKeyword) {
        filtered = filtered.filter(item => {
          // 根据实际数据结构调整搜索字段
          const searchText = `实验${item.experNum}次,总实验时长${(item.timeLab / 60).toFixed(1)}h`;
          return searchText.includes(this.searchKeyword);
        });
      }

      // 设备筛选(如果selectedEquip不为0,即非"所有设备")
      if (this.selectedEquip !== 0) {
        // 根据实际业务逻辑调整
        filtered = filtered.filter(item => {
          // 假设item有equipId字段
          return item.equipId === this.selectedEquip;
        });
      }

      // 日志级别筛选(如果selectedLevel不为0,即非"全部")
      if (this.selectedLevel !== 0) {
        // 根据实际业务逻辑调整
        filtered = filtered.filter(item => {
          // 假设item有level字段
          return item.level === this.selectedLevel;
        });
      }

      // 日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0]);
        const endDate = new Date(this.dateRange[1]);
        filtered = filtered.filter(item => {
          // 假设item有date字段
          const itemDate = new Date(item.date);
          return itemDate >= startDate && itemDate <= endDate;
        });
      }

      this.filteredDiaryRecord = filtered;
    },

    //列表日志日期
    getWeekday(index) {
      const currentDate = new Date();
      const currentDay = currentDate.getDay();
      const currentMonth = currentDate.getMonth() + 1;
      if(this.index==0){
        const newcurrentDay = (currentDay + 6) % 7;
        const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六','周日'];
        if(this.filteredDiaryRecord.length > newcurrentDay + 1){
          this.filteredDiaryRecord = this.filteredDiaryRecord.slice(0, newcurrentDay + 1);
        }
        return weekdays[index % 7];
      }else if(this.index==1){
        let currentDay = currentDate.getDate();
        const detailDay = [];
        for (let i = 1; i <= 31; i++) {
          detailDay[i] = i;
        }
        if(this.filteredDiaryRecord.length>currentDay+1){
          this.filteredDiaryRecord = this.filteredDiaryRecord.slice(0, currentDay);
        }
        return currentMonth+'.'+detailDay[index%31+1]
      }else if(this.index==2){
        const month=['1月', '2月', '3月', '4月', '5月', '6月','7月','8月','9月','10月','11月','12月']
        if(this.filteredDiaryRecord.length>currentMonth+1){
          this.filteredDiaryRecord = this.filteredDiaryRecord.slice(0, currentMonth);
        }
        return month[index%12]
      }else{
        const year = currentDate.getFullYear();
        let month = currentDate.getMonth() + 1;
        month = month < 10 ? '0' + month : month;
        let day = currentDate.getDate();
        day = day < 10 ? '0' + day : day;
        const localDate = `${year}-${month}-${day}`;
        return localDate
      }
    }

  }
};
</script>

<style scoped lang="css">
.page {
  background-color: #f7f7f7;
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100%;
}

.mt-23 {
  margin-top: 47.92rpx;
}

.ml-15 {
  margin-left: 31.25rpx;
}

.ml-26 {
  margin-left: 54.17rpx;
}

.mt-16 {
  margin-top: 33.33rpx;
}

.pos {
  position: absolute;
  left: 0;
  right: 0;
  top: 29.17rpx;
  background-color:#f7f7f7;
}

/* 用户活跃度卡片样式 */
.chart-card {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  padding: 30rpx 24rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  border: solid 2rpx #138f8720;
  margin-top: 30rpx;
  margin-left: 30rpx;
  margin-right: 30rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
}

.charts-box {
  background: #fff;
  border-radius: 12.5rpx;
  height: 500rpx;
  width: 100%;
}

/* 修改卡片样式,与addmyexper.vue保持一致 */
.infocard_full {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  padding: 30rpx 24rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  border: solid 2rpx #138f8720;
  margin-top: 30rpx;
  margin-left: 30rpx;
  margin-right: 30rpx;
  overflow: hidden;
}

/* 新增:搜索框和刷新按钮容器 */
.search-refresh-container {
  margin-bottom: 20rpx;
  gap: 20rpx;
}

/* 修改:搜索框样式 */
.search-box {
  flex: 1;
}

.search-input {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  background-color: #f7f8fa;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.search-input:focus {
  background-color: #fff;
  border-color: #138f87;
}

/* 修改:刷新按钮样式 */
.refresh-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 20rpx 24rpx;
  background-color: #138f87;
  border-radius: 8rpx;
  cursor: pointer;
  white-space: nowrap;
}

.refresh-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.refresh-text {
  color: #ffffff;
  font-size: 28rpx;
  font-family: AlibabaPuHuiTi;
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #fafafa;
  border-radius: 8rpx;
}

.filter-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20rpx;
}

.filter-item:last-child {
  margin-bottom: 0;
}

.filter-label {
  font-size: 28rpx;
  color: #333;
  min-width: 160rpx;
  font-family: AlibabaPuHuiTi;
}

.filter-select {
  flex: 1;
}

.date-picker {
  flex: 1;
}

.text_13 {
  color: #383838;
  font-size: 37.5rpx;
  font-family: AlibabaPuHuiTi;
  line-height: 26.77rpx;
}

.group_10 {
  margin-right: 500rpx;
  padding-left: 80rpx;
}

.image_4 {
  border-radius: 8.33rpx;
  filter: drop-shadow(0rpx 0rpx 10.42rpx #0000001a);
  width: 41.67rpx;
  height: 41.67rpx;
  padding-left: 0rpx;
}

.font_4 {
  font-size: 29.17rpx;
  font-family: AlibabaPuHuiTi;
  line-height: 21.71rpx;
  color: #000000;
}

.text_14 {
  margin-left: 12.5rpx;
  line-height: 26.48rpx;
}

.image_5 {
  margin-left: 29.17rpx;
  width: 45.83rpx;
  height: 45.83rpx;
}

.text_15 {
  margin-left: 12.5rpx;
  line-height: 21.9rpx;
}

.image_6 {
  margin-left: 20.83rpx;
  width: 41.67rpx;
  height: 41.67rpx;
}

.text_16 {
  line-height: 21.6rpx;
}

.group_12 {
  width: 16.67rpx;
}

.group_11 {
  margin: 50rpx 0;
}

.font_6 {
  font-size: 29.17rpx;
  font-family: AlibabaPuHuiTi;
  line-height: 21.71rpx;
  color: #808080;
}

.font_5 {
  font-size: 29.17rpx;
  font-family: AlibabaPuHuiTi;
  line-height: 35.42rpx;
  color: #808080;
}

.group_14 {
  margin-bottom: 8.33rpx;
  padding-top: 104.17rpx;
  width: 16.67rpx;
}

.range {
  width: 25%;
  margin-top: -6.5%;
}

/* 添加卡片头部样式,与addmyexper.vue保持一致 */
.card-header {
  display: flex;
  align-items: center;
  padding: 0 10rpx;
  margin-bottom: 10rpx;
  margin-top: 20rpx;
}

.section_11 {
  background-color: #138f87;
  border-radius: 14.58rpx;
  width: 8.33rpx;
  height: 29.42rpx;
  margin-right: 20rpx;
}

.text_10 {
  color: #000000;
  font-size: 29.33rpx;
  font-family: WenQuanYiMicroHeiMono;
  line-height: 22.29rpx;
}
</style>